<?php


namespace app\api\controller\v13;


use app\api\controller\Common;
use app\common\cachemodel\AppVersion;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\model\User;
use think\Log;

class Auth2 extends Common
{
    /**
     * 登录用户的基本信息
     * @var array
     */
    public $user = null;
    public $is_apple_pay = false;
    public $is_apple_check = false;
    public $apple_pay_sandbox_model = false;
    public $android_audit_mode_swtich = false;
    public $apple_goods = [];
    public $active = [];
    public $recode = [];
    public $is_cached;// redis开关
    public $cache_time;// 缓存有效期

    /**
     * 初始化
     * @throws ApiException
     * @throws \Exception
     */
    protected function _initialize()
    {
        parent::_initialize();

        $this->apple_goods = config('apple_pay_goods');

        //获取app当前版本信息
        $AppVersion = (new AppVersion())->getVersionInfo($this->headers['app-type'], $this->headers['version'], ['is_apple_pay', 'version_name', 'android_audit_mode_swtich', 'extend']);

        $AppVersion['is_apple_pay'] = $AppVersion['is_apple_pay'] ?? 0;
        $this->android_audit_mode_swtich = $AppVersion['android_audit_mode_swtich'] ?? 0;//获取安卓审核模式
        $AppVersion['apple_goods'] = $AppVersion['apple_goods'] ?? 0;
        $AppVersion['version_name'] = $AppVersion['version_name'] ?? 'V' . $this->headers['version'];
        // 判断当前ios版本是否开启苹果审核
        if ($this->headers['app-type'] === 'ios')
        {
            if ('V' . $this->headers['version'] === $AppVersion['version_name'])
            {
                // 控制苹果商品显示
                if ($AppVersion['apple_goods'])
                {
                    $this->is_apple_pay = true;
                }
                // 控制苹果审核模式
                if ($AppVersion['is_apple_pay'])
                {
                    $this->is_apple_check = true;
                }
                if (isset($AppVersion['extend']) && $AppVersion['extend'])
                {
                    $extend = json_decode($AppVersion['extend'], true);
                } else
                {
                    $extend = [];
                }
                $AppVersion['apple_pay_sandbox_model'] = $extend['ios']['apple_pay_sandbox_model'] ?? false;
                // 获取苹果沙箱状态
                if ($AppVersion['apple_pay_sandbox_model'])
                {
                    $this->apple_pay_sandbox_model = true;
                }
            }
        }
        $this->isLogin();

        if ($this->user && $this->isMustBindTel())
        {
//            Log::write('根据网络安全法要求，请先绑定手机号：' . json_encode(request()->header()), 'error', true);
            throw new ApiException('根据网络安全法要求，请先绑定手机号', 200, 407);
        }
    }

    /**
     * 判定是否登录
     * @throws ApiException
     */
    public function isLogin()
    {
        if (!isset($this->headers['access-token']) || $this->headers['access-token'] == '') return false;
        // access-token AES解密
        $accessUserToken = (new Aes())->decryptWithOpenssl($this->headers['access-token']);

        if (empty($accessUserToken)) return false;

        if (!preg_match('/||/', $accessUserToken))
        {
            throw new ApiException('您的账户登录过期，请重新登录。', 200, config('code.denied'));
        }

        [$token, $id] = explode("||", $accessUserToken);

        $id = (int)($id);
        // 账号模拟
        $simulation = config('app.simulation');

        if ($id !== $simulation['from'])
        {
            $map['id'] = $id;
            $map['token'] = $token;
        } else
        {
            $map['id'] = $simulation['to'] ?: $id;
        }

        $userinfo = (new User())->getUserinfo($map);

        if (!$userinfo || empty($userinfo))
        {
            throw new ApiException('当前账号登录过期，请您重新登录。', 200, config('code.denied'));
        }

        if ($userinfo['forbidden'] == 1)
        {
            throw new ApiException('您的账户登录过期，请重新登录。', 200, config('code.denied'));
        }

        // 判定时间是否过期
        if (time() > $userinfo['token_expire'] && isset($map['token']))
        {
            throw new ApiException('您的账户登录过期，请重新登录。', 200, config('code.denied'));
        }

        $this->user = $userinfo;
        /**
         * 定义全局常量 UID 方便日志打印带上用户ID信息
         */
        if (!defined('USERINFO_UID'))
        {
            define('USERINFO_UID', $userinfo['id']);
        }

        return true;
    }
}
